import Vue from 'vue'
import Router from 'vue-router'
import routes from './route'
import store from '../store/index'
import dynamicRoute from './dynamicRoute'
// ^3.1版本，处理push，replace路由不传，onResolve，onReject报错问题
const originalPush = Router.prototype.push
Router.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
const originalReplace = Router.prototype.replace
Router.prototype.replace = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => err)
}
Vue.use(Router)
const router = new Router({
  routes: routes,
  mode: 'history'
})
let isLoad = false
router.beforeResolve((to, from, next) => {
  if (!isLoad && store.state.login) {
    isLoad = true
    router.addRoutes(dynamicRoute(store.getters.isEcommerce))
    console.log(router)
    let redirectedFrom = to.redirectedFrom
    if (redirectedFrom && from.path === '/') {
      // 满足条件说明是在设置或在线咨询刷新的，动态路由加载后重新push路由
      let moduleArr = redirectedFrom.split('/')
      if (moduleArr[2] === 'webchat') {
        next({ path: '/index/' + moduleArr[2] + '/webchat_todo' })
      } else if (moduleArr[2] === 'config' || moduleArr[2] === 'newConfig') {
        next({ path: '/index/' + moduleArr[2] })
      }
    }
  }
  next()
})

export default router
